package main

import (
	"net"
	"strings"
)

type User struct {
	Name string
	Addr string
	C chan string
	conn net.Conn

	Ser *Server
}

//创建一个用户的api
func NewUser(con net.Conn, server *Server) *User {

	userAddr := con.RemoteAddr().String()
	user := &User{
		Name: userAddr,
		Addr: userAddr,
		C	: make(chan string),
		conn: con,
		Ser: server,
	}

	go user.ListenMessage()
	return user
}

func (u *User) onLine()  {

	u.Ser.mapLock.Lock()
	u.Ser.OnlineMap[u.Name] = u
	u.Ser.mapLock.Unlock()

	u.Ser.BroadCast(u, "已上线")
}

func (u *User) offLine() {

	u.Ser.mapLock.Lock()
	delete(u.Ser.OnlineMap, u.Name)
	u.Ser.mapLock.Unlock()

	u.Ser.BroadCast(u, "已下线")
}

func (u *User) sendMsg(msg string)  {

	u.conn.Write([]byte(msg))

}

func (u *User) doMessage(msg string)  {

	if msg == "who" {
		u.Ser.mapLock.Lock()
		for _, user := range u.Ser.OnlineMap {
			onlineMsg := "[" + user.Addr + "]" + user.Name + ": 在线...\n"
			u.sendMsg(onlineMsg)
		}
		u.Ser.mapLock.Unlock()
	} else if strings.HasPrefix(msg, "rename|") {
		newName := strings.Split(msg, "|")[1]
		_, ok := u.Ser.OnlineMap[newName]
		if ok {
			u.sendMsg("名称已存在")
		} else {
			u.Ser.mapLock.Lock()
			delete(u.Ser.OnlineMap, u.Name)
			u.Ser.OnlineMap[newName] = u
			u.Ser.mapLock.Unlock()
			u.Name = newName
			u.sendMsg("已经更新用户名 :" + u.Name)
		}
	} else if strings.HasPrefix(msg,"to|") {
		//“to|张三|你好啊，我是...
		msgs := strings.Split(msg,"|")
		toName := msgs[1]
		if toName == "" {
			u.sendMsg("消息格式不正确")
		}
		remoteUser, ok := u.Ser.OnlineMap[toName]
		if !ok {
			u.sendMsg("该用户不存在")
		}
		content := msgs[2]
		if content == "" {
			 u.sendMsg("消息内容不能为空")
		}
		remoteUser.sendMsg(u.Name + "对您说: " + content)

	} else {
		u.Ser.BroadCast(u, msg)
	}
}

//监听当前user channel 一旦有消息发送给客户端
func (u *User) ListenMessage() {

	for  {
		msg := <-u.C
		u.conn.Write([]byte(msg + "\n"))
	}
}

